package com.szgd.controller;

import com.google.gson.Gson;
import com.szgd.bean.SysDict;
import com.szgd.service.equipment.EquipEnterExitService;
import com.szgd.service.equipment.EquipmentService;
import com.szgd.service.gatherEquip.GatherEquipService;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.personnel.EnterExitService;
import com.szgd.service.personnel.PersonnelInfoService;
import com.szgd.service.personnel.TrainService;
import com.szgd.service.sys.SysDictService;
import com.szgd.service.vehicle.VehicleEnterExitService;
import com.szgd.service.vehicle.VehicleService;
import com.szgd.service.weixin.WeChatService;
import com.szgd.timer.PersonnelEnterExitRecordSynTimer;
import com.szgd.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Controller
@RequestMapping(value = "/syn")
public class SynController extends BaseController  {
    private static Logger logger = Logger.getLogger(SynController.class);

    @Autowired
    GatherEquipService gatherEquipService;
    @Autowired
    EnterExitService enterExitService;
    @Autowired
    VehicleService vehicleService;
    @Autowired
    VehicleEnterExitService vehicleEnterExitService;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    EquipEnterExitService equipEnterExitService;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    PersonnelInfoService personnelInfoService;
    @Autowired
    AttachService attachService;
    @Autowired
    FileUtil fileUtil;
    @Autowired
    TrainService trainService;

    private ArrayList<SysDict> plateTypeList = new ArrayList<SysDict>();
    private ArrayList<SysDict> colorTypeList = new ArrayList<SysDict>();
    private ArrayList<SysDict> vehicleBrandList = new ArrayList<SysDict>();
    private ArrayList<SysDict> vehicleSizeList = new ArrayList<SysDict>();
    private static String localToken="";

    @RequestMapping(value = "/synVehicleAndEquipEnterExitRecord", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object>  synVehicleEnterExitRecord(HttpServletResponse response, HttpServletRequest request, HttpSession session){
        Map<String, Object> paramMap = getMapParams(request);
        String vehicleEnterExitRecordSynFlag = PropertiesUtil.get("VehicleAndEquipEnterExitRecordSynFlag");
        if (vehicleEnterExitRecordSynFlag.equalsIgnoreCase("0"))
        {
            String message = "没有启动车辆设备识别记录导入！";
            logger.info(message);
            return getErrorMap(message);
        }

        String ip = paramMap.get("ip")==null?"":paramMap.get("ip").toString();
        String plateNumber = paramMap.get("plateNumber")==null?"":paramMap.get("plateNumber").toString().trim();
        String plateType = paramMap.get("plateType")==null?"":paramMap.get("plateType").toString();
        String plateColor = paramMap.get("plateColor")==null?"":paramMap.get("plateColor").toString();
        String vehicleBrand = paramMap.get("vehicleBrand")==null?"":paramMap.get("vehicleBrand").toString();
        String vehicleColor = paramMap.get("vehicleColor")==null?"":paramMap.get("vehicleColor").toString();
        String vehicleSize = paramMap.get("vehicleSize")==null?null:paramMap.get("vehicleSize").toString();
        String passTime = paramMap.get("passTime")==null?null:paramMap.get("passTime").toString();//图片抓拍时间:格式YYYYMMDDHHMMSSmmm(年月日时分秒毫秒)*/

        String imgBase64 = paramMap.get("imgBase64")==null?null:paramMap.get("imgBase64").toString();

        logger.info("进入车辆识别回调接口，IP:"+ip+"，车牌号:"+plateNumber);
        if (passTime != null)
        {
            /*DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            long time = Long.parseLong(passTime);
            passTime = dtf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));*/

            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            /*passTime = passTime.substring(0,14);
            try {
                passTime = sdf2.format(sdf1.parse(passTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }*/
            passTime = sdf2.format(new Date());

        }
        if (plateTypeList.size()==0)
        {
            plateTypeList = (ArrayList<SysDict>)sysDictService.getByParentCode("PLATE_TYPE");
        }
        if (colorTypeList.size()==0)
        {
            colorTypeList = (ArrayList<SysDict>)sysDictService.getByParentCode("COLOR_TYPE");
        }
        if (vehicleBrandList.size()==0)
        {
            vehicleBrandList = (ArrayList<SysDict>)sysDictService.getByParentCode("VEHICLE_BRAND");
        }

        if (vehicleSizeList.size()==0)
        {
            vehicleSizeList = (ArrayList<SysDict>)sysDictService.getByParentCode("VEHICLE_SIZE");
        }
        /*plateTypeList = (ArrayList<SysDict>)session.getAttribute("PLATE_TYPE");
        colorTypeList = (ArrayList<SysDict>)session.getAttribute("COLOR_TYPE");
        vehicleBrandList = (ArrayList<SysDict>)session.getAttribute("VEHICLE_BRAND");
        vehicleSizeList = (ArrayList<SysDict>)session.getAttribute("VEHICLE_SIZE");*/

        for (int i = 0; i < plateTypeList.size(); i++) {
            SysDict sd = plateTypeList.get(i);
            if (sd.getOtherValue().equalsIgnoreCase(plateType))
            {
                plateType = sd.getCode();
                break;
            }
        }
        for (int i = 0; i < colorTypeList.size(); i++) {
            SysDict sd = colorTypeList.get(i);
            if (sd.getOtherValue().equalsIgnoreCase(plateColor))
            {
                plateColor = sd.getCode();
                break;
            }
        }
        for (int i = 0; i < vehicleBrandList.size(); i++) {
            SysDict sd = vehicleBrandList.get(i);
            if (sd.getOtherValue().equalsIgnoreCase(vehicleBrand))
            {
                vehicleBrand = sd.getCode();
                break;
            }
        }

        for (int i = 0; i < vehicleSizeList.size(); i++) {
            SysDict sd = vehicleSizeList.get(i);
            if (sd.getOtherValue().equalsIgnoreCase(vehicleSize))
            {
                vehicleSize = sd.getCode();
                break;
            }
        }
        Map<String, Object> paramsMap = new HashMap<>();

        paramsMap.put("equipNumber",plateNumber);
        Map<String, Object> equipmentMap = equipmentService.getEquipment(paramsMap);
        if (equipmentMap != null && equipmentMap.get("id") != null)
        {
            logger.info("进入设备同步");
            String name = null;
            String path = null;
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String date = df.format(new Date());
            try {
                name = fileUtil.uploadFile(imgBase64,"plateNumber.jpeg",date,PropertiesUtil.get("snapImagePath"));//base64抓拍图片保存
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (name != null)
            {
                path = SysUtil.getDateStr(null,"yyyyMM");
            }

            equipEnterExitService.synEquipEnterExitRecord(equipmentMap.get("id").toString(),equipmentMap.get("equipNumber").toString(),ip,passTime,name,path);

        }else
        {
            logger.info("进入车辆同步");
            paramsMap.put("plateNumber",plateNumber);
            Map<String, Object> vehicleInfoMap = vehicleService.getVehicleInfo(paramsMap);
            String vehicleId =  null;
            if (vehicleInfoMap != null  && vehicleInfoMap.get("id") != null )
                vehicleId = vehicleInfoMap.get("id").toString();
            else
            {
                Map<String, Object> vehicleParamsMap = new HashMap<>();
                vehicleParamsMap.put("vehicleId",vehicleId);
                vehicleParamsMap.put("plateNumber",plateNumber);
                vehicleParamsMap.put("plateType",plateType);
                vehicleParamsMap.put("plateColor",plateColor);
                vehicleParamsMap.put("vehicleBrand",vehicleBrand);
                vehicleParamsMap.put("vehicleColor",vehicleColor);
                vehicleParamsMap.put("vehicleSize",vehicleSize);
                vehicleParamsMap.put("creator","syn");
                vehicleService.insertVehicleInfo(vehicleParamsMap);
                vehicleId = vehicleParamsMap.get("id").toString();
            }

            String name = null;
            String path = null;
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String date = df.format(new Date());
            try {
                name = fileUtil.uploadFile(imgBase64,plateNumber+".jpeg",date,PropertiesUtil.get("snapImagePath"));//base64抓拍图片保存
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (name != null)
            {
                path = SysUtil.getDateStr(null,"yyyyMM");
            }

            vehicleEnterExitService.synVehicleEnterExitRecord(vehicleId,plateNumber,plateType,plateColor,vehicleBrand,vehicleColor,vehicleSize,ip,passTime,name,path);
        }


        String message = "车辆/设备识别记录导入成功！";
        logger.info(message);
        return getSuccMap(message);
    }

    @RequestMapping(value = "/heartbeat", method = RequestMethod.POST)
    @ResponseBody
    public String  heartbeat(HttpServletResponse response, HttpServletRequest request, HttpSession session){
        Map<String, Object> paramMap = getMapParams(request);


        String device_id = paramMap.get("device_id")==null?"":paramMap.get("device_id").toString();//SZFT030
        String timestamp = paramMap.get("timestamp")==null?"":paramMap.get("timestamp").toString();//1489116844
        String version = paramMap.get("version")==null?"":paramMap.get("version").toString();//1.0.0
        String sign = paramMap.get("sign")==null?"":paramMap.get("sign").toString();

        Gson gson = new Gson();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("code",0);
        resultMap.put("message","success");
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("version","1.1.0");
        dataMap.put("timestamp",System.currentTimeMillis());
        resultMap.put("data",dataMap);
        String resutJson = gson.toJson(resultMap);
        return resutJson;
    }

    @RequestMapping(value = "/auth", method = RequestMethod.POST)
    @ResponseBody
    public String  auth(HttpServletResponse response, HttpServletRequest request, HttpSession session){
        System.out.println("----auth:"+ new Date().toString());
        Map<String, Object> paramMap = getMapParams(request);
        String device_id = paramMap.get("device_id")==null?"":paramMap.get("device_id").toString();//SZFT030
        String timestamp = paramMap.get("timestamp")==null?"":paramMap.get("timestamp").toString();//1489116844
        String version = paramMap.get("version")==null?"":paramMap.get("version").toString();//1.0.0
        String sign = paramMap.get("sign")==null?"":paramMap.get("sign").toString();
        System.out.println("device_id:"+ device_id);
        String timeMillis = String.valueOf(System.currentTimeMillis());
        localToken = AEncryptHelper.encrypt(timeMillis,"szgd");
        Gson gson = new Gson();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("code",0);
        resultMap.put("message","success");
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("token",localToken);
        dataMap.put("timestamp",System.currentTimeMillis());
        dataMap.put("version","1.1.0");
        System.out.println("token:"+localToken);
        resultMap.put("data",dataMap);
        String resutJson = gson.toJson(resultMap);
        return resutJson;
    }

    @RequestMapping(value = "/upload_data_full", method = RequestMethod.POST)
    @ResponseBody
    public String  upload_data_full(HttpServletResponse response, HttpServletRequest request, HttpSession session){
        System.out.println("----upload_data_full:"+ new Date().toString());
        Map<String, Object> paramMap = getMapParams(request);

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String device_id = paramMap.get("device_id")==null?"":paramMap.get("device_id").toString();
        System.out.println("device_id:"+ device_id);
        String remoteToken = paramMap.get("token")==null?"":paramMap.get("token").toString();
        String card_type = paramMap.get("card_type")==null?null:paramMap.get("card_type").toString();//证件类型，身份证为“” 港澳台居民居住证为“J”，外国人永久居留证“I”
        String name = paramMap.get("name")==null?"":paramMap.get("name").toString();
        String sex = paramMap.get("sex")==null?null:paramMap.get("sex").toString();//性别: 0-男; 1-女
        String nation = paramMap.get("nation")==null?"":paramMap.get("nation").toString();//民族（身份证专有，其余证件时为“”）
        String birthday = paramMap.get("birthday")==null?null:paramMap.get("birthday").toString();//出生年月日如：20170310
        String address = paramMap.get("address")==null?"":paramMap.get("address").toString();
        String id_number = paramMap.get("id_number")==null?"":paramMap.get("id_number").toString();//证件号码
        String authority = paramMap.get("authority")==null?"":paramMap.get("authority").toString();//签发机关
        String validity = paramMap.get("validity")==null?null:paramMap.get("validity").toString();//有效期限如：20170310-20370310
        String verify_result = paramMap.get("verify_result")==null?"":paramMap.get("verify_result").toString();//认证结果：0-成功； 1-失败； 2-真人检测失败；4-指纹校验失败； 5-OCR校验失败
        String face_image = paramMap.get("face_image")==null?"":paramMap.get("face_image").toString();//现场拍摄人脸Base64编码字符串(不含\n，可解码为jpg)
        String verify_time = paramMap.get("verify_time")==null?null:paramMap.get("verify_time").toString();//认证时间，客户端的时间戳(毫秒级)
        if (!localToken.equalsIgnoreCase(remoteToken)||remoteToken.length()==0)
        {
            logger.info("token is invalid");
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("code",401);
            resultMap.put("message","token is invalid");
            System.out.println(remoteToken+"| token is invalid-"+ new Date().toString());
            return new Gson().toJson(resultMap);
        }
        if (verify_result==null || !verify_result.equalsIgnoreCase("0"))
        {
            logger.info("verify_result is failed");
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("code",402);
            resultMap.put("message","verify_result is failed");
            System.out.println(verify_result+"| verify_result is failed-"+ new Date().toString());
            return new Gson().toJson(resultMap);
        }
        if (id_number.length()==0)
        {
            logger.info("id_number is null");
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("code",403);
            resultMap.put("message","id_number is null");
            System.out.println(id_number+"| id_number is failed-"+ new Date().toString());
            return new Gson().toJson(resultMap);
        }
        if (name.length()==0)
        {
            logger.info("name is null");
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("code",404);
            resultMap.put("message","name is null");
            System.out.println(name+"| name is failed-"+ new Date().toString());
            return new Gson().toJson(resultMap);
        }
        if (face_image.length()==0)
        {
            logger.info("face_image is null");
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("code",405);
            resultMap.put("message","face_image is null");
            return new Gson().toJson(resultMap);
        }

        Map<String, Object> params = new HashMap<>();
        Map<String, Object> trainRecordMap = new HashMap<>();//培训记录
        trainRecordMap.put("deviceId",device_id);
        if (verify_time != null)
        {
            long verifyTime = Long.valueOf(verify_time);
            verify_time = sdf3.format(new Date(verifyTime));
            trainRecordMap.put("passTime",verify_time);
        }

        if (card_type != null)
        {
            if (card_type.length() == 0)
                card_type = "ID_CARD";
            else if (card_type.equalsIgnoreCase("J"))
                card_type = "ID_HMT_CARD";
            else if (card_type.equalsIgnoreCase("I"))
                card_type = "ID_FPRC";

        }
        /*System.out.println("remoteToken:"+remoteToken);
        System.out.println("id_number:"+id_number);*/

        params.put("idType",card_type);
        params.put("name",name);

        if (sex != null)
        {
            if (sex.equalsIgnoreCase("0"))
                sex = "1";
            else if (sex.equalsIgnoreCase("1"))
                sex = "0";

        }
        params.put("sex",sex);
        params.put("nation",nation);
        if (birthday != null)
        {
            try {
                birthday = sdf1.format(sdf1.parse(birthday));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        params.put("birthday",birthday);
        params.put("censusRegisterAddress",address);
        params.put("idNumber",id_number);
        //params.put("authority",authority);

        if (validity != null)
        {
            validity = validity.split("-")[1];
            try {
                validity = sdf1.format(sdf1.parse(validity));
            } catch (ParseException e) {
                e.printStackTrace();
                validity = null;
            }
        }
        params.put("idInvalidTime",validity);

        Map<String, Object> personMap = personnelInfoService.getPersonnelInfoByIdNumber(id_number);
        if (personMap != null)//更新,暂不更新基本信息
        {
            params.put("uploader","syn");
            params.put("id",personMap.get("id"));
            /*personnelInfoService.updatePersonnelInfo(params);*/
            trainRecordMap.put("personnelId",params.get("id"));
            trainService.insertTrainRecord(trainRecordMap);
            Gson gson = new Gson();
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("code",0);
            resultMap.put("message","upload successful");
            String resutJson = gson.toJson(resultMap);
            return resutJson;


        }else//插入
        {
            params.put("creator","syn");
            params.put("isEnterSite",1);//需要进入工地，说明要人脸识别
            personnelInfoService.insertPersonnelInfo(params);
            trainRecordMap.put("personnelId",params.get("id"));
            trainService.insertTrainRecord(trainRecordMap);
        }


        //System.out.println("face_image:"+face_image);
        //保存图片
        Map<String, Object> headPictureAttachMap = new  HashMap<String, Object>();

        if (personMap != null)
            headPictureAttachMap.put("id",personMap.get("headPictureId"));
        else
            headPictureAttachMap.put("id",null);
        headPictureAttachMap.put("parentId",params.get("id"));
        String filename = name+"_"+id_number + ".jpg";
        headPictureAttachMap.put("type","ATTACH_PIC");
        headPictureAttachMap.put("source","ATTACH_PERSONNEL_INFO");

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = df.format(new Date());
        try {
            String newFileName = fileUtil.uploadFile(face_image,filename,date,PropertiesUtil.get("uploadPath"));
            headPictureAttachMap.put("name",newFileName);
            Map<String, Object> attachMap = attachService.saveAttach(headPictureAttachMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("code",0);
        resultMap.put("message","upload successful");
        String resutJson = gson.toJson(resultMap);
        logger.info("upload successful");
        return resutJson;
    }

    /**
     * 人脸识别回调函数
     * @param response
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/identifyCallBack", method = RequestMethod.POST)
    @ResponseBody
    public String  identifyCallBack(HttpServletResponse response, HttpServletRequest request, HttpSession session){

        String personnelEnterExitRecordSynFlag = PropertiesUtil.get("PersonnelEnterExitRecordSynFlag");
        if (personnelEnterExitRecordSynFlag.equalsIgnoreCase("0"))
        {
            logger.info("没有打开人脸识别标识");
            Gson gson = new Gson();
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("result",1);
            resultMap.put("success",true);
            String resutJson = gson.toJson(resultMap);
            return resutJson;
        }
        ;
        Map<String, Object> paramMap = getMapParams(request);
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String ip = paramMap.get("ip")==null?"":paramMap.get("ip").toString();//设备IP地址
        String deviceKey = paramMap.get("deviceKey")==null?"":paramMap.get("deviceKey").toString();//设备出厂唯一标识码
        String personId = paramMap.get("personId")==null?"":paramMap.get("personId").toString();//人员id，陌生人为STRANGERBABY
        String time = paramMap.get("time")==null?"":paramMap.get("time").toString();//识别记录时间戳（以设备时间为准）
        String type = paramMap.get("type")==null?"":paramMap.get("type").toString();//•	识别方式（face/card）、识别出的人员类型
                                                                                    //•	face_0（表示是人脸识别，且该人员在passtime权限时间内），card_1(表示是刷卡识别，且该人员在passtime权限时间外)，face_2（表示是人脸识别，且识别失败或识别到的是陌生人）
        logger.info("进入人脸设备回调接口，IP:"+ip);
        String path = paramMap.get("path")==null?"":paramMap.get("path").toString();//现场照在设备内的保存路径，访问此url需设备局域网在线，且发送请求的客户端与设备处于局域网同一网段
        if (!type.equalsIgnoreCase("face_0"))//如果非合法识别，则返回
        {
            logger.info(ip+":非法人脸识别结果，不作处理:"+type);
            Gson gson = new Gson();
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("result",1);
            resultMap.put("success",true);
            String resutJson = gson.toJson(resultMap);
            return resutJson;
        }

        List<Map<String, Object>>  peopleGatherEquipList = gatherEquipService.getPeopleGatherEquipList();
        Map<String, Object> peopleGatherEquipMap = null;
        for (int i = 0; i < peopleGatherEquipList.size(); i++) {
            Map<String, Object> tempMap = peopleGatherEquipList.get(i);
            if (tempMap.get("ip").toString().equalsIgnoreCase(ip))
                peopleGatherEquipMap = tempMap;
        }
        if (peopleGatherEquipMap == null)
        {
            logger.info("数据库里没有此次识别结果对应的ip："+ip);
            Gson gson = new Gson();
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("result",1);
            resultMap.put("success",true);
            String resutJson = gson.toJson(resultMap);
            return resutJson;
        }
        Gson gson = new Gson();
        Map<String,Object> resultMap = new HashMap<String,Object>();

        String siteId = peopleGatherEquipMap.get("siteId").toString();
        String gatherEquipId = peopleGatherEquipMap.get("id").toString();
        String password = peopleGatherEquipMap.get("password").toString();
        int passFlag  = Integer.parseInt(peopleGatherEquipMap.get("passFlag").toString());

        Map<String,Object> paramEnterOrExitMap = new HashMap<String,Object>();
        paramEnterOrExitMap.put("siteId",siteId);
        paramEnterOrExitMap.put("personId",personId);
        paramEnterOrExitMap.put("passFlag",passFlag);
        enterExitService.insertEnterExitRecordFrom(password,ip,passFlag,siteId,gatherEquipId,time,personId,path);
        //五分钟内不插入记录
        Map<String, Object> enterOrExitMap= enterExitService.getLastEnterOrExitInfo(paramEnterOrExitMap);
        if (enterOrExitMap != null)
        {
            String lastTime = enterOrExitMap.get("createTime").toString();
            try {
                Date lastDate = sdf3.parse(lastTime);
                long different = new Date().getTime() - lastDate.getTime();
                long secondsInMilli = 1000;
                /*long minutesInMilli = secondsInMilli * 60;
                long hoursInMilli = minutesInMilli * 60;
                long daysInMilli = hoursInMilli * 24;*/

                /*long elapsedDays = different / daysInMilli;
                different = different % daysInMilli;

                long elapsedHours = different / hoursInMilli;
                different = different % hoursInMilli;

                long elapsedMinutes = different / minutesInMilli;
                different = different % minutesInMilli;*/

                long elapsedSeconds = different / secondsInMilli;
                long personnelEnterExitRecordSynInterval = Long.parseLong(PropertiesUtil.get("PersonnelEnterExitRecordSynInterval"));
                if (elapsedSeconds <= personnelEnterExitRecordSynInterval)
                {
                    logger.info("此人员距离上次同步相差"+elapsedSeconds+"秒，不用保存");
                    resultMap.put("result",1);
                    resultMap.put("success",true);
                    String resutJson = gson.toJson(resultMap);
                    return resutJson;
                }else {
                    logger.info("此人员距离上次同步相差"+elapsedSeconds+"秒,大于"+personnelEnterExitRecordSynInterval+"秒，需要保存");
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else
        {
            logger.info("此人员是第一次同步");
        }

        logger.info("开始同步人员进出闸机数据!ip："+ip);
        String projectId = peopleGatherEquipMap.get("projectId")==null?null:peopleGatherEquipMap.get("projectId").toString();
        String workSiteId = peopleGatherEquipMap.get("workSiteId")==null?null:peopleGatherEquipMap.get("workSiteId").toString();


        int result = enterExitService.synEnterExitRecord_EX(password,ip,passFlag,siteId,gatherEquipId,time,personId,path);
        logger.info("结束同步信息：ip："+ip+", 进出标识："+passFlag);
        if (result == 0)
            logger.info("同步人员进出记录失败：数据库里没找到人员ID"+personId+" 对应的人员信息");


        if (result > -1)//如果等于0表示人员表里没找到对应的人员，不插入，但是也算成功返回。
        {
            resultMap.put("result",1);
            resultMap.put("success",true);
        }else
        {
            resultMap.put("result",0);
            resultMap.put("success",false);
        }
        String resutJson = gson.toJson(resultMap);
        logger.info("同步完成返回："+resutJson);
        return resutJson;

    }

    public static void main(String[] args) {
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String lastTime = "2019-07-17 12:41:15";
        String nowTime = "2019-07-17 12:42:15";
        Date lastDate = null;
        try {
            lastDate = sdf3.parse(lastTime);
            long different = sdf3.parse(nowTime).getTime() - lastDate.getTime();
            long secondsInMilli = 1000;
            long elapsedSeconds = different / secondsInMilli;
            long personnelEnterExitRecordSynInterval = Long.parseLong(PropertiesUtil.get("PersonnelEnterExitRecordSynInterval"));
            System.out.println(elapsedSeconds);
            System.out.println(personnelEnterExitRecordSynInterval);
            if (elapsedSeconds <= personnelEnterExitRecordSynInterval)
            {
                System.out.println("小于5分");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

                /*long minutesInMilli = secondsInMilli * 60;
                long hoursInMilli = minutesInMilli * 60;
                long daysInMilli = hoursInMilli * 24;*/

                /*long elapsedDays = different / daysInMilli;
                different = different % daysInMilli;

                long elapsedHours = different / hoursInMilli;
                different = different % hoursInMilli;

                long elapsedMinutes = different / minutesInMilli;
                different = different % minutesInMilli;*/


    }
}
